"""
    Author:
    Date: 2019-01-11

    投诉管理类
"""

from entities.consts import *
from utils import db
from utils.log import Log

TABLE_NAME = 'cmf_users_complaint'


def agree(cid):
    """ 接受用户举报 """
    record = get_complaint(cid)
    if record is None:
        return False

    if record['auth_status'] != AUTH_STATUS_WAITING:
        Log.error(f'Agree complaint-{cid} failed for status!')
        return False

    return update_complaint_auth_status(cid, AUTH_STATUS_CERTIFIED)


def reject(cid):
    """ 拒绝用户举报 """
    record = get_complaint(cid)
    if record is None:
        return False

    if record['auth_status'] != AUTH_STATUS_WAITING:
        Log.error(f'Reject complaint-{cid} failed for status!')
        return False

    return update_complaint_auth_status(cid, AUTH_STATUS_REJECTED)


def get_complaint_records_count(auth_status):
    """ 获取审核中的投诉记录 """
    sql = f'''
        SELECT      COUNT(*) as count
        FROM        {TABLE_NAME}
        WHERE       auth_status={auth_status};
    '''
    data = db.query_data_from_db(sql)
    return data[0]['count'] if data else 0


def get_complaint_records(auth_status):
    """ 获取指定状态的投诉记录 """
    sql = f'''
        SELECT      *,
                    c.id AS cid,
                    u2.avatar AS reporter_avatar
        FROM        {TABLE_NAME} AS c
        JOIN        cmf_users AS u on c.target_uid=u.id
        JOIN        cmf_users AS u2 ON c.uid=u2.id
        WHERE       auth_status={auth_status} AND c.review=0
        ORDER BY    cid DESC;
    '''
    data = db.query_data_from_db(sql)
    return data if data else []


def get_complaint(cid):
    """ 获取指定id的投诉记录 """
    sql = f'''
        SELECT      *,
                    c.id AS cid
        FROM        {TABLE_NAME} AS c
        JOIN        cmf_users AS u on c.target_uid=u.id
        WHERE       c.id={cid};
    '''
    data = db.query_data_from_db(sql)
    return data[0] if data else None


def update_complaint_auth_status(cid, auth_status):
    """ 更新举报记录的认证状态 """
    sql = f'''
        UPDATE      {TABLE_NAME}
        SET         auth_status={auth_status}
        WHERE       id={cid}
        LIMIT       1;
    '''
    affected_rows = db.execute_sql(sql)
    return affected_rows == 1


if __name__ == '__main__':
    print('ok')
